package com.recipedb.recipedb.service.impl;

import com.recipedb.recipedb.entity.User;
import com.recipedb.recipedb.repository.UserRepository;
import com.recipedb.recipedb.service.UserService;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    private final String avatarPath = "/var/www/recipe-app/uploads/users/avatar/";

    @Autowired
    private UserRepository userRepository;

    @Override
    public User save(User user) {
        return userRepository.save(user);
    }

    @Override
    public void deleteById(Long id) {
        userRepository.deleteById(id);
    }

    @Override
    public Optional<User> findById(Long id) {
        return userRepository.findById(id);
    }

    @Override
    public List<User> findAll() {
        return userRepository.findAll();
    }

    /**
     * 查询用户，不存在返回 null
     */
    @Override
    public User findByUsername(String username) {
        return userRepository.findByUsername(username).orElse(null);
    }

    @Override
    public boolean existsByUsername(String username) {
        return userRepository.existsByUsername(username);
    }

    @Override
    @Transactional
    public User updateUsername(Long userId, String newUsername) {
        return userRepository.findById(userId)
                .map(user -> {
                    user.setUsername(newUsername);
                    return userRepository.save(user);
                })
                .orElse(null);
    }

    @Override
    public Long getUserIdByUsername(String username) {
        User user = findByUsername(username);
        return user != null ? user.getId() : null;
    }

    @Override
    public List<User> getUsersByUidOrUsername(String uid, String username) {
        return userRepository.findByUidOrUsername(uid, username);
    }

    @Override
    public void incrementFollowCount(Long userId) {
        userRepository.incrementFollowCount(userId);
    }

    @Override
    public void decrementFollowCount(Long userId) {
        userRepository.decrementFollowCount(userId);
    }

    @Override
    public void incrementFanCount(Long userId) {
        userRepository.incrementFanCount(userId);
    }

    @Override
    public void decrementFanCount(Long userId) {
        userRepository.decrementFanCount(userId);
    }

    @Override
    public void incrementLikeCount(Long userId) {
        userRepository.incrementLikeCount(userId);
    }

    @Override
    public void decrementLikeCount(Long userId) {
        userRepository.decrementLikeCount(userId);
    }

    @Override
    public String updateAvatar(long id, MultipartFile file) {
        User user = userRepository.findById(id).orElse(null);
        if (user == null) return null;

        String oldAvatar = user.getAvatar();
        String uid = user.getUid();
        long ts = System.currentTimeMillis() / 1000;
        long slice = ts - (ts % 30);

        String newFileName = uid + "_" + slice + ".jpg";
        File target = new File(avatarPath + newFileName);

        try {
            file.transferTo(target);
        } catch (IOException e) {
            throw new RuntimeException("Upload avatar failed", e);
        }

        user.setAvatar("/uploads/users/avatar/" + newFileName);
        userRepository.save(user);

        deleteOldAvatar(oldAvatar);
        return user.getAvatar();
    }

    private void deleteOldAvatar(String oldAvatar) {
        if (oldAvatar == null || oldAvatar.endsWith("default.jpg")) return;

        String fileName = oldAvatar.substring(oldAvatar.lastIndexOf('/') + 1);
        File oldFile = new File(avatarPath + fileName);
        if (oldFile.exists()) oldFile.delete();
    }
}
